use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct WebCfg {
    pub host: String,
    pub port: String,
}
#[derive(Deserialize, Debug)]
pub struct DbCfg {
    pub url: String,
}
#[derive(Deserialize, Debug)]
pub struct Configuration {
    pub jwt: JWT,
    pub web: WebCfg,
    pub database: DbCfg,
    pub session: RedisSession,
}
#[derive(Deserialize, Debug)]
pub struct RedisSession {
    pub url: String,
}
#[derive(Deserialize, Debug)]
pub struct JWT {
    admin_secret_key: String,
    ttl: i64,
    token_name: String,
}

impl Configuration {
    pub fn from_env() -> Result<Self, anyhow::Error> {
        let config_result: Result<config::Config, config::ConfigError> = config::Config::builder()
            .add_source(config::Environment::default())
            .build();

        match config_result {
            Ok(config) => {
                let cfg: Result<Configuration, config::ConfigError> = config.try_deserialize();
                Ok(cfg?)
            }
            Err(err) => Err(anyhow::Error::msg(err)),
        }
    }
}
